package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean checkData(String data, Integer type) {
        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                if (StringUtils.isNotEmpty(data)) {
                    throw new LyException(400, "查询参数有误");
                }
                break;
            case 2:
                colName = "phone";
                if (!RegexUtils.isPhone(data)) {
                    throw new LyException(400, "查询参数有误");
                }
                break;
            default:
                throw new LyException(400, "查询参数有误");

        }

        return this.query().eq(colName, data).count() == 1;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "ly.user.verify:";

    @Override
    public void sendVerifyCode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }
        Map<String, String> msg = new HashMap<>();

        msg.put("phone", phone);
        // 2.使用Apache的工具类生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);

        msg.put("code", code);
        //消息发送
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

        String key = KEY_PREFIX + phone;
        //验证码redis存储
        this.redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public void createUser(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        //判断如果验证码为空。或不匹配，
        if (StringUtils.isEmpty(code) || !code.equals(redisTemplate.opsForValue())) {
            throw new LyException(400, "验证码有误");
        }

        //对密码进行加密，生成随机盐值，优点，盐值不外露
        String encodePassword = passwordEncoder.encode(user.getPassword());

        //首先会根据算法，推测密文的盐值，拿着盐值，对密码的明文加密，加密后匹配两个加密密码信息
        //passwordEncoder.matches("heima114",encodePassword);

        user.setPassword(encodePassword);
        //保存用户信息
        this.save(user);
    }

    @Override
    public UserDTO queryUser(String username, String password) {
        User user = query().eq("username", username).one();
        if (null == user) {
            throw new LyException(400, "用户名不存在");
        }

        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new LyException(400, "密码输入错误");
        }
        return new UserDTO(user);
    }

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public UserDetail checkLogin(String token) {

        Payload payload = jwtUtils.parseJwt(token);

        UserDetail userDetail = payload.getUserDetail();

        return userDetail;
    }


}
